Page({
  data: {
    list: [],
    active: 1,
    listData: [],
    vancelltext: true,
    show: true,
  },
  getTabs(ev) {
    this.setData({
      active: ev.detail.index,
    })
    this.getListData()
  },
  async onLoad() {
    this.getHomeList()
  },
  async getHomeList() {
    const res = await wx.http.get('http://toutiao.itheima.net/v1_0/channels')
    this.setData({
      list: res.data.channels,
    })
    this.setData({
      active: res.data.channels[0].id,
    })
    this.getListData()
  },
  async getListData() {
    const {
      data: { pre_timestamp, results },
    } = await wx.http.get('http://toutiao.itheima.net/v1_0/articles', {
      channel_id: this.data.active,
      timestamp: +new Date(),
    })
    this.timestampToYear(results)
  },
  timestampToYear(results) {
    // 获取当前时间
    const now = new Date()
    for (let item in results) {
      // console.log(results[item].pubdate);
      // 获取需求时间
      const demandTime = new Date(results[item].pubdate)
      // 计算时间差
      const temporal = now.getTime() - demandTime.getTime()
      // 计算年份差
      const diffYear = Math.floor(temporal / (1000 * 60 * 60 * 24 * 365))
      results[item].pubdate = diffYear
      // console.log(results[item].pubdate);
      // console.log(results[item]);
    }

    this.setData({
      listData: results,
    })
  },
  goSearch() {
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },
})
